#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2025/04/15 13:22
# @File           : views.py
# @IDE            : PyCharm
# @desc           : 路由，视图文件

from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import APIRouter, Depends
from . import models, schemas, crud, params
from core.dependencies import IdList
from apps.vadmin.auth.utils.current import AllUserAuth
from utils.response import SuccessResponse
from apps.vadmin.auth.utils.validation.auth import Auth
from core.database import db_getter
from apps.device.camera.models import Camera
from apps.location.room.models import Room
from sqlalchemy.orm import joinedload
from .schemas import RoomSimpleOut, RoomOut

app = APIRouter()


###########################################################
#    房间
###########################################################
@app.get("/room", summary="获取房间列表", tags=["房间"])
async def get_room_list(p: params.RoomParams = Depends(), auth: Auth = Depends(AllUserAuth())):
    datas, count = await crud.RoomDal(auth.db).get_datas(**p.dict(), v_return_count=True)
    return SuccessResponse(datas, count=count)


@app.get("/room/detailed", summary="获取详细房间列表", description="获取房间列表的同时带上包含的摄像头列表", tags=["房间"])
async def get_room_list(p: params.RoomParams = Depends(), auth: Auth = Depends(AllUserAuth())):
    # 使用 joinedload 预加载摄像头数据
    # 这里 Room 模型中有 cameras 关系，表示与 Camera 模型的关联
    v_options = [joinedload(Room.cameras)]
    datas, count = await crud.RoomDal(auth.db).get_datas(
        **p.dict(),
        v_options=v_options,
        v_schema=RoomOut,
        v_return_count=True
    )
    return SuccessResponse(datas, count=count)


@app.post("/room", summary="创建房间", tags=["房间"])
async def create_room(data: schemas.Room, auth: Auth = Depends(AllUserAuth())):
    return SuccessResponse(await crud.RoomDal(auth.db).create_data(data=data))


@app.delete("/room", summary="删除房间", description="硬删除", tags=["房间"])
async def delete_room_list(ids: IdList = Depends(), auth: Auth = Depends(AllUserAuth())):
    await crud.RoomDal(auth.db).delete_datas(ids=ids.ids, v_soft=False)
    return SuccessResponse("删除成功")


@app.put("/room/{data_id}", summary="更新房间", tags=["房间"])
async def put_room(data_id: int, data: schemas.Room, auth: Auth = Depends(AllUserAuth())):
    return SuccessResponse(await crud.RoomDal(auth.db).put_data(data_id, data))


@app.get("/room/{data_id}", summary="获取房间信息", tags=["房间"])
async def get_room(data_id: int, db: AsyncSession = Depends(db_getter)):
    schema = schemas.RoomOut
    v_options = [joinedload(Room.cameras)]
    return SuccessResponse(
        await crud.RoomDal(db).get_data(
            data_id,
            v_options=v_options,
            v_schema=schema))
